<template>
  <div class="jq-table h-full flex-col">
    <SearchForm @handle-reset-form-datas="handleResetFormDatas" :searchForm="searchForm" @handle-search="handleSearch"
      @chanFormValue="chanFormValue" />
    <div class="page-card h-full" v-loading="loading">
      <JqTable :tableColumn="tableColumn" :tableButtons="tableButtons" :itemsButtons="itemsButtons" :data="tableData"
        :showPagination="false">
        <template #menuName>
          <el-table-column  :min-width="220" prop="menuType" label="名称" fit="true"
            show-header="true" align="left" >
            <template #default="scope">
              <div style="display:inline-flex;align-items: center;align-items: baseline">
                <Icon :name="scope.row.menuIcon" size="18" style="transform: translateY(3px);margin-right: 5px"  v-if="scope.row.menuIcon" />
                <span>{{ scope.row.menuName }}</span>
              </div>
            </template>
          </el-table-column>
        </template>
        <template #menuType>
          <el-table-column show-overflow-tooltip :min-width="80" prop="menuType" label="类型" fit="true"
            show-header="true" align="left">
            <template #default="scope">
              <div style="display: flex; align-items: center">
                <span>{{ scope.row.menuType === 1 ? '目录' : scope.row.menuType === 2 ? '菜单' : '按钮' }}</span>
              </div>
            </template>
          </el-table-column>
        </template>
        <template #isInstitution>
          <el-table-column show-overflow-tooltip :min-width="80" prop="isInstitution" label="是否机构" fit="true"
            show-header="true" align="left">
            <template #default="scope">
              <div style="display: flex; align-items: center">
                <el-switch v-model="scope.row.isInstitution" :active-value="1" :inactive-value="0"
                  @change="setIs('isInstitution', scope.row)" />
                <!-- <span>{{ scope.row.isInstitution === 1 ? '是' :  '否' }}</span> -->
              </div>
            </template>
          </el-table-column>
        </template>
        <template #isHealthDoctor>
          <el-table-column show-overflow-tooltip :min-width="80" prop="isHealthDoctor" label="健康顾问" fit="true"
            show-header="true" align="left">
            <template #default="scope">
              <div style="display: flex; align-items: center">
                <el-switch v-model="scope.row.isHealthDoctor" :active-value="1" :inactive-value="0"
                  @change="setIs('isHealthDoctor', scope.row)" />
                <!-- <span>{{ scope.row.isHealthDoctor === 1 ? '是' :  '否' }}</span> -->
              </div>
            </template>
          </el-table-column>
        </template>
        <template #visible>
          <el-table-column show-overflow-tooltip :min-width="80" prop="visible" label="状态" fit="true" show-header="true"
            align="left">
            <template #default="scope">
              <div style="display: flex; align-items: center">
                <!-- <el-switch v-model="scope.row.visible" :active-value="0" :inactive-value="1"
                  @change="setIs('visible', scope.row)" /> -->
                <span :class="scope.row.visible === 0 ? 'point1' : 'point2'"></span>
                <span>{{ scope.row.visible === 0 ? '显示' :  '隐藏' }}</span>
              </div>
            </template>
          </el-table-column>
        </template>
      </JqTable>
      <AddOrUpdateForStaff ref="addOrUpdateRef" @update-list="updateList" />
    </div>
  </div>
</template>

<script lang="ts" setup>
defineOptions({ name: 'SystemMenu' }); // 菜单管理
import { reactive, ref, onBeforeMount, computed } from 'vue';

import {
  getMenuTreeList,
  deleteMenuById,
  editMenuStatus,
} from '@/api/system/menu/index'
import { getMenuList } from '@/api/auth';
import { JqTable } from '@/components/Table/index';
import AddOrUpdateForStaff from '@/views/system/menu/components/add-or-update/index.vue';
import { useRouteStore } from '@/store';
const routeStore = useRouteStore();

const currentMenudatas = computed(() => routeStore.currentMenudatas); //路由btn
import {
  orgOptionsRequest,
} from '@/api/common'; //公共接口
import { storage } from '@/utils/storage';
const addOrUpdateRef = ref();
let searchFormParams = reactive({});
let orgIdDatas = reactive([]);
interface Row {
  id: number;
  status: number;
  statusConfig: object;
  menuName: String;
  menuType: number;
}
// 搜索字段
let searchForm = reactive([
  {
    type: 'input',
    value: '',
    label: '名称',
    placeholder: '请输入名称',
    eName: 'menuName'
  },
  {
    type: 'select',
    value: '',
    label: '状态',
    options: () => {
      return [
        { id: 0, name: '显示' },
        { id: 1, name: '隐藏' }];
    },
    eName: 'visible'
  },
  {
    type: 'select',
    value: '',
    label: '是否健康顾问',
    options: () => {
      return [
        { id: 1, name: '是' },
        { id: 0, name: '否' }];
    },
    eName: 'isHealthDoctor'
  },
  {
    type: 'select',
    value: '',
    label: '是否机构',
    options: () => {
      return [
        { id: 1, name: '是' },
        { id: 0, name: '否' }];
    },
    eName: 'isInstitution'
  }
]);
// table列表字段
const tableColumn = reactive([
  { label: '名称', prop: 'menuName', minWidth: '220',slot: true },
  { label: '权限标识', prop: 'perms', minWidth: '220' },
  { label: '类型', prop: 'menuType', minWidth: '120', slot: true },
  { label: '组件路径', prop: 'path', minWidth: '170' },
  { label: '排序', prop: 'orderNum', minWidth: '60' },
  { label: '是否机构', prop: 'isInstitution', minWidth: '80', slot: true },
  { label: '健康顾问', prop: 'isHealthDoctor', minWidth: '120', slot: true },
  { label: '创建时间', prop: 'createTime', minWidth: '140' },
  { label: '最后一次操作时间', prop: 'updateTime', minWidth: '140' },
  { label: '状态', prop: 'visible', minWidth: '140', slot: true },
]);
let tableButtons = reactive([
  {
    id: 43,
    type: 'primary',
    label: '添加',
    perms: 'sys:menu:btn:create',
    onClick: () => {
      onAddOrUpdate({});
    }
  },
]);

let timer: any = null
let paramsList: any = []
const setIs = (paramsString: any, row: any) => {
  const index = paramsList.findIndex((item: any) => item.id === row.id)
  const rowPar = {
    id: row.id,
    isInstitution: row.isInstitution,
    isHealthDoctor: row.isHealthDoctor,
    visible: row.visible,
  }
  if (index !== -1) {
    paramsList[index] = rowPar
  } else {
    paramsList.push(rowPar)
  }
  timer && clearTimeout(timer)
  timer = setTimeout(() => {
    console.log('测试', paramsList);
    editMenuStatus(paramsList).then(async res => {
      ElMessage.success('修改成功！')
      const menuList = await getMenuList({});
      console.log(menuList.data);
      const menus = JSON.stringify(menuList.data)
      storage.set('menu', menus);
      window.location.reload()
    })
  }, 1500);
}
const onAddOrUpdate = (data?: Recordable) => {
  // addOrUpdateRef.value.handleDialog(true);
  addOrUpdateRef.value.init(data, 'tableAdd');
};
let itemsButtons = reactive([
  {
    id: 44,
    type: 'primary',
    perms: 'sys:menu:btn:view',
    label: '查看',
    // onClick: (row: any) => {
    //   setDialogDefaultDatas(row, 'check');
    // }
    onClick: (row: Row) => {
      addOrUpdateRef.value.init(row, 'check')
    }
  },
  {
    id: 44,
    type: 'primary',
    perms: 'sys:menu:btn:add',
    label: '新增',
    onClick: (row: Row) => {
      if (row.menuType === 3) {
        ElMessage.warning('按钮不需添加菜单')
        return
      }
      const addRow = { parentId: row.id, parentName: row.menuName, menuType: row.menuType }
      addOrUpdateRef.value.init(addRow, 'add')
    }
  },
  {
    id: 45,
    type: 'primary',
    perms: 'sys:menu:btn:edit',
    label: '编辑',
    onClick: (row: Row) => {
      addOrUpdateRef.value.init(row, 'edit')
    }
  },
  {
    id: 47,
    type: 'primary',
    perms: 'sys:menu:btn:del',
    label: '删除',
    onClick: (row: []) => {
      deleteRow(row);
    }
  },
]);

const tableData = ref([])
const loading = ref(false)
const getList = () => {
  loading.value = true
  getMenuTreeList(searchFormParams).then(res => {
    console.log(res, 'res');
    tableData.value = res.data
    loading.value = false
  })
}
getList()
// 组织下拉
const getOrgOptionsDatas = async () => {
  const data: any = await orgOptionsRequest({ containBase: true });
  orgIdDatas = data.data;
};
// 数据筛选
const handleSearch = (searchFormParamsDatats: {}) => {
  Object.assign(searchFormParams, searchFormParamsDatats);
  getList();
};
/*清除表单值 */
const chanFormValue = (formParamsDatats: {}) => {
  searchFormParams = formParamsDatats;
};
// 新建事件 end
const tableButtonsPermission = (datas: any[], datas1: any[]) => {
  return datas.filter(function (item1: { perms: string }) {
    return datas1.find(function (item2: { perms: string }) {
      return item1.perms === item2.perms;
    });
  });
};
const deleteRow = (rowData: any) => {
  ElMessageBox.confirm('请确认是否删除？', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    const data: any = await deleteMenuById({ id: rowData.id });
    if (data.code === 2000) {
      ElMessage.success('已删除');
      getList();
    } else {
      ElMessage.error(data?.message);
      return;
    }
    return;
  });
  // .catch(() => {
  //   ElMessage({
  //     type: 'info',
  //     message: '取消操作'
  //   });
  // });
};
/* 高级搜索重置 */
const handleResetFormDatas = () => {
  searchFormParams = {};
  console.log(searchForm);

  searchForm = searchForm.map((item) => {
    if (item.value || item.value === 0) {
      item.value = '';
    }
    return item;
  });
  getList();
};
const updateList = () => {
  getList();
};
// 学历下拉
onBeforeMount(() => {
  if (!currentMenudatas.value) {
    return
  }
  tableButtons = tableButtonsPermission(tableButtons, currentMenudatas.value?.tableButtons); //tableButtons根据数据返回按钮信息控制权限
  itemsButtons = tableButtonsPermission(itemsButtons, currentMenudatas.value?.itemsButtons); //itemButtons根据数据返回按钮信息控制权限
});
// 调用
getOrgOptionsDatas();
</script>
<style scoped>
.packageCardcontainer {
  display: flex;
  flex-wrap: wrap;
  align-content: flex-start;

  >.card {
    flex: 0 0 18%;
    min-width: 18%;
    margin-right: calc(9.99% / 4);
    margin-bottom: 10px;

    /* // 每行最后一个卡片 */
    &:nth-child(5n) {
      margin-right: 0;
    }

    /* // 最后一个卡片 */
    &:last-child {
      margin-right: auto;
    }
  }
}
</style>
